package me.flyray.bsin.server.impl;


import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import me.flyray.bsin.constants.ResponseCode;
import me.flyray.bsin.context.BsinServiceContext;
import me.flyray.bsin.domain.entity.AgentCard;
import me.flyray.bsin.domain.entity.EmbeddingModel;
import me.flyray.bsin.exception.BusinessException;
import me.flyray.bsin.facade.service.AgentService;
import me.flyray.bsin.infrastructure.mapper.AgentCardMapper;
import me.flyray.bsin.mybatis.utils.Pagination;
import me.flyray.bsin.security.contex.LoginInfoContextHelper;
import me.flyray.bsin.security.domain.LoginUser;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shenyu.client.apache.dubbo.annotation.ShenyuDubboService;
import org.apache.shenyu.client.apidocs.annotations.ApiDoc;
import org.apache.shenyu.client.apidocs.annotations.ApiModule;
import org.apache.shenyu.client.dubbo.common.annotation.ShenyuDubboClient;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;
import java.util.Map;
import java.util.Optional;

import static me.flyray.bsin.constants.ResponseCode.*;

@Slf4j
@ShenyuDubboService(path = "/aiAgent", timeout = 6000)
@ApiModule(value = "aiAgent")
public class AgentServiceImpl implements AgentService {

    @Autowired
    private AgentCardMapper agentCardMapper;

    @ApiDoc(desc = "create")
    @ShenyuDubboClient("/create")
    @Override
    public void create(Map<String, Object> requestMap) {
        LoginUser loginUser = LoginInfoContextHelper.getLoginUser();
        AgentCard agentCard = BsinServiceContext.getReqBodyDto(AgentCard.class, requestMap);
        Optional.ofNullable(agentCard.getTenantId())
                .or(() -> Optional.ofNullable(loginUser.getTenantId()))
                .ifPresentOrElse(
                        agentCard::setTenantId,
                        () -> { throw new BusinessException(ResponseCode.TENANT_ID_NOT_ISNULL); }
                );
        // 校验DID在创建智能体
        agentCardMapper.insert(agentCard);
    }

    @ApiDoc(desc = "edit")
    @ShenyuDubboClient("/edit")
    @Override
    public void edit(Map<String, Object> requestMap) {
        AgentCard agentCard = BsinServiceContext.getReqBodyDto(AgentCard.class, requestMap);
        if (agentCardMapper.updateById(agentCard) == 0){
            throw new BusinessException(ID_NOT_ISNULL);
        }
    }

    @ApiDoc(desc = "delete")
    @ShenyuDubboClient("/delete")
    @Override
    public void delete(Map<String, Object> requestMap) {
        String serialNo = MapUtils.getString(requestMap, "serialNo");
        if (agentCardMapper.deleteById(serialNo) == 0){
            throw new BusinessException(ID_NOT_ISNULL);
        }
    }

    @ApiDoc(desc = "getDetail")
    @ShenyuDubboClient("/getDetail")
    @Override
    public AgentCard getDetail(Map<String, Object> requestMap) {
        String serialNo = MapUtils.getString(requestMap, "serialNo");
        LoginUser loginUser = LoginInfoContextHelper.getLoginUser();
        String bizRoleTypeNo = null;
        if (serialNo == null) {
            bizRoleTypeNo = loginUser.getBizRoleTypeNo();
            if(bizRoleTypeNo == null){
                throw new BusinessException(ResponseCode.CUSTOMER_NO_NOT_ISNULL);
            }
        }
        AgentCard agentCard = agentCardMapper.selectOne(new LambdaQueryWrapper<AgentCard>()
                .eq(AgentCard::getTenantId, loginUser.getTenantId())
                .eq(StringUtils.isNotBlank(serialNo), AgentCard::getSerialNo, serialNo)
                .eq(StringUtils.isNotBlank(bizRoleTypeNo), AgentCard::getCustomerNo, bizRoleTypeNo));
        if (agentCard == null) {
            throw new BusinessException(CONDITION_NOT_EXISTS);
        }
        return agentCard;
    }

    @ApiDoc(desc = "getPageList")
    @ShenyuDubboClient("/getPageList")
    @Override
    public IPage<?> getPageList(Map<String, Object> requestMap) {
        LoginUser loginUser = LoginInfoContextHelper.getLoginUser();
        AgentCard agentCard = BsinServiceContext.getReqBodyDto(AgentCard.class, requestMap);
        Object paginationObj =  requestMap.get("pagination");
        Pagination pagination = new Pagination();
        BeanUtil.copyProperties(paginationObj,pagination);

        Page<AgentCard> page = new Page<>(pagination.getPageNum(),pagination.getPageSize());
        LambdaQueryWrapper<AgentCard> warapper = new LambdaQueryWrapper<>();
        warapper.orderByDesc(AgentCard::getCreateTime);
        warapper.eq(AgentCard::getTenantId, loginUser.getTenantId());
        warapper.eq(StringUtils.isNotBlank(loginUser.getMerchantNo()), AgentCard::getMerchantNo, loginUser.getMerchantNo());
        warapper.eq(StringUtils.isNotBlank(agentCard.getAgentType()), AgentCard::getAgentType, agentCard.getAgentType());
        IPage<AgentCard> pageList = agentCardMapper.selectPage(page,warapper);
        return pageList;
    }

    @ApiDoc(desc = "getList")
    @ShenyuDubboClient("/getList")
    @Override
    public List<AgentCard> getList(Map<String, Object> requestMap) {
        AgentCard agentCard = BsinServiceContext.getReqBodyDto(AgentCard.class, requestMap);
        String tenantId = (String) requestMap.get("tenantId");
        LambdaQueryWrapper<AgentCard> warapper = new LambdaQueryWrapper<>();
        warapper.eq(AgentCard::getTenantId, tenantId);
        List<AgentCard> agentCardList = agentCardMapper.selectList(warapper);
        return agentCardList;
    }

}
